const { build } = require("esbuild");
const fs = require("fs-extra");
const path = require("path");

const { normalizePath } = require("../utils");
const scanImports = require("./scan");

async function createOptimizeDepsRun(config) {
  // 分析项目中依赖了哪些第三方库
  const deps = await scanImports(config);

  const { cacheDir } = config;
  // node_modules/.vite/deps
  const depsCacheDir = path.resolve(cacheDir, "deps");
  const metadataPath = path.join(depsCacheDir, "_metadata.json");

  const metadata = {
    optimized: {},
  };

  for (const id in deps) {
    const entry = deps[id];
    const file = normalizePath(path.resolve(depsCacheDir, id + ".js"));
    metadata.optimized[id] = {
      src: entry, // "../../vue/dist/vue.runtime.esm-bundler.js",
      file, // "vue.js",
    };
    await build({
      absWorkingDir: process.cwd(),
      entryPoints: [deps[id]],
      outfile: file,
      bundle: true,
      write: true,
      format: "esm",
    });
  }

  console.log("metadata", metadata);
  await fs.ensureDir(depsCacheDir);
  await fs.writeFileSync(
    metadataPath,
    JSON.stringify(
      metadata,
      (key, value) => {
        if (key === "file" || key === "src") {
          return path.relative(depsCacheDir, value);
        }
        return value;
      },
      2
    )
  );
  return { metadata };
}

module.exports = {
  createOptimizeDepsRun,
};
